package cn.gcyl.module.biz.service.platformregistrationinformation;

import cn.gcyl.module.biz.controller.admin.conferenceregistrationinformation.vo.ConferenceMeetingInformationPageReqVO;
import cn.gcyl.module.biz.dal.dataobject.SysMemberUserDO;
import cn.gcyl.module.biz.dal.dataobject.columntype.ColumnTypeDO;
import cn.gcyl.module.biz.dal.dataobject.conferenceregistrationinformation.ConferenceUserRegistrationInformationPO;
import cn.gcyl.module.biz.dal.dataobject.platforminformation.PlatformInformationDO;
import cn.gcyl.module.biz.dal.dataobject.platformregistrationinformation.PlatformUserRegistrationInformationPO;
import cn.gcyl.module.biz.dal.dataobject.useractionlog.UserActionLogDO;
import cn.gcyl.module.biz.dal.mysql.SysMemberUserMapper;
import cn.gcyl.module.biz.dal.mysql.columntype.ColumnTypeMapper;
import cn.gcyl.module.biz.dal.mysql.platforminformation.PlatformInformationMapper;
import cn.gcyl.module.biz.dal.mysql.useractionlog.UserActionLogMapper;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.gcyl.module.biz.controller.admin.platformregistrationinformation.vo.*;
import cn.gcyl.module.biz.dal.dataobject.platformregistrationinformation.PlatformRegistrationInformationDO;
import cn.gcyl.framework.common.pojo.PageResult;
import cn.gcyl.framework.common.pojo.PageParam;
import cn.gcyl.framework.common.util.object.BeanUtils;

import cn.gcyl.module.biz.dal.mysql.platformregistrationinformation.PlatformRegistrationInformationMapper;

import static cn.gcyl.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.gcyl.framework.common.util.collection.CollectionUtils.convertList;
import static cn.gcyl.framework.common.util.collection.CollectionUtils.diffList;
import static cn.gcyl.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.gcyl.module.system.enums.ErrorCodeConstants.*;

/**
 * 平台报名信息 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class PlatformRegistrationInformationServiceImpl implements PlatformRegistrationInformationService {

    @Resource
    private PlatformRegistrationInformationMapper platformRegistrationInformationMapper;
    @Resource
    private SysMemberUserMapper sysMemberUserMapper;
    @Resource
    private PlatformInformationMapper platformInformationMapper;
    @Resource
    private UserActionLogMapper userActionLogMapper;
    @Resource
    private ColumnTypeMapper columnTypeMapper;

    @Override
    public Long createAppPlatformRegistrationInformation(AppPlatformUserRegistrationReqVO createReqVO) {
        Long loginUserId = getLoginUserId();
        // 插入
        PlatformRegistrationInformationDO platformRegistrationInformation = BeanUtils.toBean(createReqVO, PlatformRegistrationInformationDO.class);
        platformRegistrationInformationMapper.insert(platformRegistrationInformation);
        PlatformInformationDO platformInformationDO = platformInformationMapper.selectById(platformRegistrationInformation.getPlatformInformationId());
        SysMemberUserDO sysMemberUserDO = sysMemberUserMapper.selectById(loginUserId);
        if (ObjectUtil.isNotEmpty(sysMemberUserDO)) {
            //判断会员是否免费  不免费则扣除次数
            ColumnTypeDO columnTypeDO = columnTypeMapper.selectOne(
                    new LambdaQueryWrapper<ColumnTypeDO>().eq(ColumnTypeDO::getColumns, createReqVO.getTitleType())
            );
            String isSignUpIds = platformInformationDO.getIsSignUpIds();
            if (ObjectUtil.isNotEmpty(isSignUpIds)) {
                // 将逗号分隔的用户ID字符串转换为列表
                List<String> userIdList = Arrays.asList(isSignUpIds.split(","));
                // 检查当前用户ID是否已存在
                if (!userIdList.contains(String.valueOf(sysMemberUserDO.getId()))) {
                    // 将当前用户ID添加到已报名用户列表中
                    String newUserIds;
                    if (ObjectUtil.isNotEmpty(isSignUpIds)) {
                        newUserIds = isSignUpIds + "," + loginUserId;
                    } else {
                        newUserIds = String.valueOf(loginUserId);
                    }
                    platformInformationDO.setIsSignUpIds(newUserIds);
                    platformInformationMapper.updateById(platformInformationDO);
                }
            }else {
                platformInformationDO.setIsSignUpIds(loginUserId.toString());
                platformInformationMapper.updateById(platformInformationDO);
            }

            if (columnTypeDO.getStatus()==1) {
                //校验会员剩余报名次数
                if (sysMemberUserDO.getRemainingRegistrationsFrequency()<=0){
                    throw exception(PLATFORM_REGISTRATION_INFORMATION_NOT_NUMBER);
                }
                //校验会员是否已经消耗一次针对该平台的报名，消耗则不再扣除次数
                String registeredUserIds = platformInformationDO.getRegisteredUserIds();
                String consultingUserIds = platformInformationDO.getConsultingUserIds();
                boolean alreadyConsulted = false;
                if (ObjectUtil.isNotEmpty(registeredUserIds)) {
                    // 将逗号分隔的用户ID字符串转换为列表
                    List<String> userIdList = Arrays.asList(registeredUserIds.split(","));
                    // 检查当前用户ID是否已存在
                    if (userIdList.contains(String.valueOf(sysMemberUserDO.getId()))) {
                        alreadyConsulted = true;
                    }
                }
                if (!alreadyConsulted) {
                    //扣除报名次数
                    sysMemberUserDO.setRemainingRegistrationsFrequency(sysMemberUserDO.getRemainingRegistrationsFrequency() - 1);
                    sysMemberUserDO.setRemainingConsultationFrequency(sysMemberUserDO.getRemainingConsultationFrequency() - 1);
                    sysMemberUserMapper.updateById(sysMemberUserDO);
                    // 将当前用户ID添加到已报名用户列表中
                    String newUserIds;
                    String newUserIdss;
                    if (ObjectUtil.isNotEmpty(registeredUserIds)) {
                        newUserIds = registeredUserIds + "," + loginUserId;
                    } else {
                        newUserIds = String.valueOf(loginUserId);
                    }
                    if (ObjectUtil.isNotEmpty(consultingUserIds)) {
                        newUserIdss = consultingUserIds + "," + loginUserId;
                    } else {
                        newUserIdss = String.valueOf(loginUserId);
                    }
                    platformInformationDO.setRegisteredUserIds(newUserIds);
                    platformInformationDO.setConsultingUserIds(newUserIdss);
                    platformInformationMapper.updateById(platformInformationDO);
                }
            }
        }
        //添加操作日志
        UserActionLogDO userActionLogDO = new UserActionLogDO();
        userActionLogDO.setUserId(loginUserId);
        userActionLogDO.setAction("报名平台信息:"+platformInformationDO.getPurchasingCompany()+"，标题："+platformInformationDO.getTitle());
        userActionLogMapper.insert(userActionLogDO);
        // 返回
        return platformRegistrationInformation.getId();
    }
    @Override
    public PlatformInformationDO createAppPlatformConsult(Long id) {
        Long loginUserId = getLoginUserId();
        SysMemberUserDO sysMemberUserDO = sysMemberUserMapper.selectById(loginUserId);
        if (ObjectUtil.isNotEmpty(sysMemberUserDO)) {
            PlatformInformationDO platformInformationDO = platformInformationMapper.selectById(id);

            //判断会员是否免费  不免费则扣除次数
            ColumnTypeDO columnTypeDO = columnTypeMapper.selectOne(
                    new LambdaQueryWrapper<ColumnTypeDO>().eq(ColumnTypeDO::getColumns, platformInformationDO.getTitleType())
            );
            if (columnTypeDO.getStatus()==1) {
                // 检查用户是否已经咨询过该平台信息
                String registeredUserIds = platformInformationDO.getConsultingUserIds();
                String registeredUserIds1 = platformInformationDO.getRegisteredUserIds();
                boolean alreadyConsulted = false;
                if (ObjectUtil.isNotEmpty(registeredUserIds)) {
                    // 将逗号分隔的用户ID字符串转换为列表
                    List<String> userIdList = Arrays.asList(registeredUserIds.split(","));
                    // 检查当前用户ID是否已存在
                    if (userIdList.contains(String.valueOf(loginUserId))) {
                        alreadyConsulted = true;
                    }
                }
                // 如果用户尚未咨询过，则扣除咨询次数
                if (!alreadyConsulted) {
                    // 校验会员剩余咨询次数
                    if (sysMemberUserDO.getRemainingConsultationFrequency() <= 0) {
                        throw exception(PLATFORM_REGISTRATION_CONSULT_NOT_NUMBER);
                    }
                    // 扣除咨询次数
                    sysMemberUserDO.setRemainingConsultationFrequency(sysMemberUserDO.getRemainingConsultationFrequency() - 1);
                    //同步扣除报名次数
                    sysMemberUserDO.setRemainingRegistrationsFrequency(sysMemberUserDO.getRemainingRegistrationsFrequency() - 1);
                    sysMemberUserMapper.updateById(sysMemberUserDO);
                    // 将当前用户ID添加到已咨询用户列表中
                    String newUserIds;
                    String newUserIdss;
                    if (ObjectUtil.isNotEmpty(registeredUserIds)) {
                        newUserIds = registeredUserIds + "," + loginUserId;
                    } else {
                        newUserIds = String.valueOf(loginUserId);
                    }
                    if (ObjectUtil.isNotEmpty(registeredUserIds1)) {
                        newUserIdss = registeredUserIds1 + "," + loginUserId;
                    } else {
                        newUserIdss = String.valueOf(loginUserId);
                    }
                    platformInformationDO.setConsultingUserIds(newUserIds);
                    platformInformationDO.setRegisteredUserIds(newUserIdss);
                    platformInformationMapper.updateById(platformInformationDO);
                }
            }
            // 添加操作日志
            UserActionLogDO userActionLogDO = new UserActionLogDO();
            userActionLogDO.setUserId(loginUserId);
            userActionLogDO.setAction("咨询平台信息:" + platformInformationDO.getPurchasingCompany() + "，标题：" + platformInformationDO.getTitle());
            userActionLogMapper.insert(userActionLogDO);

            return platformInformationDO;
        }
        // 返回
        return null;
    }

    @Override
    public Long createPlatformRegistrationInformation(PlatformRegistrationInformationSaveReqVO createReqVO) {
        // 插入
        PlatformRegistrationInformationDO platformRegistrationInformation = BeanUtils.toBean(createReqVO, PlatformRegistrationInformationDO.class);
        platformRegistrationInformationMapper.insert(platformRegistrationInformation);

        // 返回
        return platformRegistrationInformation.getId();
    }

    @Override
    public void updatePlatformRegistrationInformation(PlatformRegistrationInformationSaveReqVO updateReqVO) {
        // 校验存在
        validatePlatformRegistrationInformationExists(updateReqVO.getId());
        // 更新
        PlatformRegistrationInformationDO updateObj = BeanUtils.toBean(updateReqVO, PlatformRegistrationInformationDO.class);
        platformRegistrationInformationMapper.updateById(updateObj);
    }

    @Override
    public void deletePlatformRegistrationInformation(Long id) {
        // 校验存在
        validatePlatformRegistrationInformationExists(id);
        // 删除
        platformRegistrationInformationMapper.deleteById(id);
    }

    @Override
        public void deletePlatformRegistrationInformationListByIds(List<Long> ids) {
        // 删除
        platformRegistrationInformationMapper.deleteByIds(ids);
        }


    private void validatePlatformRegistrationInformationExists(Long id) {
        if (platformRegistrationInformationMapper.selectById(id) == null) {
            throw exception(PLATFORM_REGISTRATION_INFORMATION_NOT_EXISTS);
        }
    }

    @Override
    public PlatformRegistrationInformationDO getPlatformRegistrationInformation(Long id) {
        return platformRegistrationInformationMapper.selectById(id);
    }

    @Override
    public PageResult<PlatformRegistrationInformationDO> getPlatformRegistrationInformationPage(PlatformRegistrationInformationPageReqVO pageReqVO) {
        return platformRegistrationInformationMapper.selectPage(pageReqVO);
    }
    @Override
    public PageResult<PlatformUserRegistrationInformationPO> getUserPlatformRegistrationInformationPage(PlatformUserRegistrationInformationPageReqVO pageReqVO) {
        List<PlatformUserRegistrationInformationPO> list = platformRegistrationInformationMapper.getUserPlatformRegistrationInformationPage(pageReqVO);
        // 使用Lambda表达式简化代码逻辑
        list.forEach(platformUserRegistrationInformationPO -> {
            List<PlatformRegistrationInformationDO> platformRegistrationInformationDOS = platformRegistrationInformationMapper.selectList(
                    new LambdaQueryWrapper<PlatformRegistrationInformationDO>()
                            .eq(PlatformRegistrationInformationDO::getUserId, platformUserRegistrationInformationPO.getUserId())
            );

            // 使用Lambda表达式更新所有相关记录的isView状态
            platformRegistrationInformationDOS.stream()
                    .filter(platformRegistrationInformationDO -> platformRegistrationInformationDO.getIsView() == null || platformRegistrationInformationDO.getIsView() != 1)
                    .forEach(platformRegistrationInformationDO -> {
                        platformRegistrationInformationDO.setIsView(1);
                        platformRegistrationInformationMapper.updateById(platformRegistrationInformationDO);
                    });
        });

        // 根据实际情况处理分页逻辑
        return new PageResult<>(list, (long) list.size());
    }

    @Override
    public PlatformUserRegistrationInformationPO getPlatformRegistrationInformationOne(PlatformUserRegistrationInformationPageReqVO pageReqVO) {
        PlatformUserRegistrationInformationPO platformRegistrationInformationOne = platformRegistrationInformationMapper.getPlatformRegistrationInformationOne(pageReqVO);
        // 根据实际情况处理分页逻辑
        return platformRegistrationInformationOne;
    }

}